package com.skivingcloud.report.datas.service.impl;

import com.skivingcloud.common.exception.BusinessException;
import com.skivingcloud.report.datas.entity.ReportDatasetTransform;
import com.skivingcloud.report.datas.mapper.ReportDatasetTransformMapper;
import com.skivingcloud.report.datas.service.IReportDatasetTransformService;
import com.skivingcloud.report.datas.service.TransformStrategy;
import com.skivingcloud.report.utils.ParamsResolverHelper;

import net.sf.json.JSONObject;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 数据集数据转换 服务实现类
 * </p>
 *
 * @author skivingcloud
 * @since 2022-07-20
 */
@Service
public class ReportDatasetTransformServiceImpl extends ServiceImpl<ReportDatasetTransformMapper, ReportDatasetTransform> implements IReportDatasetTransformService, InitializingBean, ApplicationContextAware {

	private final Map<String, TransformStrategy> queryServiceImplMap = new HashMap<>();
    private ApplicationContext applicationContext;
	
	@Override
    public List<JsonNode> transform(List<ReportDatasetTransform> dataSetTransformDtoList, List<JsonNode> data) throws Exception {
        if (dataSetTransformDtoList == null || dataSetTransformDtoList.isEmpty()) {
            return data;
        }

        for (ReportDatasetTransform dataSetTransformDto : dataSetTransformDtoList) {
            data = getTarget(dataSetTransformDto.getTransformType()).transform(dataSetTransformDto, data);
        }
        return data;
    }

	public TransformStrategy getTarget(String type) {
        return queryServiceImplMap.get(type);
    }

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		Map<String, TransformStrategy> beanMap = applicationContext.getBeansOfType(TransformStrategy.class);
        //遍历该接口的所有实现，将其放入map中
        for (TransformStrategy serviceImpl : beanMap.values()) {
            queryServiceImplMap.put(serviceImpl.type(), serviceImpl);
        }
	}
}
